<template>
  <a-modal
    :title="title"
    :width="modalWidth()"
    :visible="visible"
    :centered="true"
    @ok="handleSubmit"
    :bodyStyle="{height: modalHeight()}"
    @cancel="handleCancel">

    <div :style="modalStyle()">
      <a-spin :spinning="confirmLoading">
        <a-form :form="form">
          <a-form-item
            label="关系名称"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            has-feedback
          >
            <a-select
              show-search
              :filter-option="searchOption"
              style="width: 98.2%"
              :getPopupContainer="
                triggerNode => {
                  return triggerNode.parentNode || document.body;
                }
              "
              placeholder="请输入关系名称"
              @change="relationChange"
              v-decorator="['relationId', {rules: [{ required: true, message: '请输入关系名称！' }]}]">
              <a-select-option v-for="(item,index) in relationList" :key="index" :value="item.id">{{ item.chName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
        <a-button icon="plus" @click="addStrategy">添加策略</a-button>
        <a-form
          :form="strategyForms[index]"
          :key="index"
          v-for="(item,index) in strategyList"
          class="ant-advanced-search-form">
          <div style="margin-left: 2%;margin-bottom: 12px;color: red">策略名称: 策略{{ index + 1 }}</div>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item
                :labelCol="centerLabelCol"
                :wrapperCol="centerWrapperCol"
                label="策略类型">
                <a-select
                  @change="(v)=>strategyTypeChange(v,item,index)"
                  :getPopupContainer="
                    triggerNode => {
                      return triggerNode.parentNode || document.body;
                    }
                  "
                  v-decorator="['strategyType' , {initialValue: item.strategyType,rules: [{required: true, message: '请选择策略类型'}]}]">
                  <a-select-option value="完全相等">完全相等</a-select-option>
                  <a-select-option value="相似度">相似度</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item
                :labelCol="centerLabelCol"
                :wrapperCol="centerWrapperCol"
                label="概念A">
                <a-input
                  v-model="item.conceptAName"
                  placeholder="请选择关系名称"
                  :disabled="true">
                </a-input>
              </a-form-item>
              <a-form-item
                :labelCol="centerLabelCol"
                :wrapperCol="centerWrapperCol"
                label="概念B">
                <a-input
                  placeholder="请选择关系名称"
                  v-model="item.conceptBName"
                  :disabled="true">
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                v-if="item.strategyType !=='完全相等'"
                :labelCol="centerLabelCol"
                :wrapperCol="centerWrapperCol"
                label="相似度:">
                <a-input-number
                  @change="(v)=>item.similarity =v"
                  v-decorator="['similarity', {initialValue:item.similarity,rules: [{required: item.strategyType ==='相似度', message: '请输入相似度'}]}]"
                  :formatter="value => `${value}%`"
                  :parser="value => value.replace('%', '')"
                  :min="1"
                  :max="99"
                  style="width: 120px"></a-input-number>
              </a-form-item>
              <a-form-item
                v-else
                :labelCol="centerLabelCol"
                :wrapperCol="centerWrapperCol"
                label="">
                <div style="height: 40px"></div>
              </a-form-item>
              <a-form-item
                :labelCol="centerLabelCol"
                :wrapperCol="centerWrapperCol"
                label="属性:">
                <a-select
                  show-search
                  :getPopupContainer="
                    triggerNode => {
                      return triggerNode.parentNode || document.body;
                    }
                  "
                  :filter-option="searchOption"
                  placeholder="请选择属性"
                  @change="v=>item.propertyA =v"
                  v-decorator="['propertyA', {rules: [{ required: true, message: '请选择属性' }]}]">
                  <a-select-option v-for="(property,i) in propertyAList" :key="i" :value="property.id">
                    {{ property.chName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item
                :labelCol="centerLabelCol"
                :wrapperCol="centerWrapperCol"
                label="属性:">
                <a-select
                  show-search
                  :getPopupContainer="
                    triggerNode => {
                      return triggerNode.parentNode || document.body;
                    }
                  "
                  @change="v=>item.propertyB =v"
                  :filter-option="searchOption"
                  placeholder="请选择属性"
                  v-decorator="['propertyB', {rules: [{ required: true, message: '请选择属性' }]}]">
                  <a-select-option v-for="(property,i) in propertyBList" :key="i" :value="property.id">
                    {{ property.chName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-button size="small" @click="removeStrategy(index)" class="rule_form_del">删除</a-button>
          </a-row>
        </a-form>
        <a-button style="display: block;margin-top: 24px" icon="plus" @click="addExtend">添加扩展</a-button>
        <a-form
          :form="extendForms[index]"
          v-for="(item ,index) in extendList"
          :key="'extend'+index"
          class="ant-advanced-search-form">
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item
                :labelCol="centerLabelCol"
                :wrapperCol="centerWrapperCol"
                label="策略">
                <a-select
                  :getPopupContainer="
                    triggerNode => {
                      return triggerNode.parentNode || document.body;
                    }
                  "
                  v-decorator="['strategyName', {rules: [{required: true, message: '请选择策略！'}]}]"
                  placeholder="请选择策略"
                >
                  <a-select-option v-for="(_,j) in strategyList" :key="j" :value="fullStrategyName(j)">策略{{ j + 1 }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item
                :labelCol="centerLabelCol"
                :wrapperCol="centerWrapperCol"
                label="字段">
                <a-input
                  placeholder="请输入字段"
                  v-decorator="['columnA', {rules: [{required: true, message: '请输入字段！'}]}]"
                ></a-input>
              </a-form-item>
              <a-form-item
                :labelCol="centerLabelCol"
                :wrapperCol="centerWrapperCol"
                label="字段">
                <a-input
                  placeholder="请输入字段"
                  v-decorator="['columnB', {rules: [{required: true, message: '请输入字段！'}]}]"
                ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                :labelCol="centerLabelCol"
                :wrapperCol="centerWrapperCol"
                label="表名:">
                <a-input
                  placeholder="请输入表名"
                  v-decorator="['tableName', {rules: [{required: true, message: '请输入表名！'}]}]"
                ></a-input>
              </a-form-item>
              <a-form-item
                :labelCol="centerLabelCol"
                :wrapperCol="centerWrapperCol"
                label="属性:">
                <a-select
                  :getPopupContainer="
                    triggerNode => {
                      return triggerNode.parentNode || document.body;
                    }
                  "
                  show-search
                  :filter-option="searchOption"
                  placeholder="请选择属性"
                  @change="v=>item.propertyA =v"
                  v-decorator="['propertyA', {rules: [{ required: true, message: '请选择属性！' }]}]">
                  <a-select-option v-for="(property,i) in propertyAList" :key="i" :value="property.id">
                    {{ property.chName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item
                :labelCol="centerLabelCol"
                :wrapperCol="centerWrapperCol"
                label="属性:">
                <a-select
                  show-search
                  :getPopupContainer="
                    triggerNode => {
                      return triggerNode.parentNode || document.body;
                    }
                  "
                  :filter-option="searchOption"
                  placeholder="请选择属性"
                  @change="v=>item.propertyA =v"
                  v-decorator="['propertyB', {rules: [{ required: true, message: '请选择属性！' }]}]">
                  <a-select-option v-for="(property,i) in propertyBList" :key="i" :value="property.id">
                    {{ property.chName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-button size="small" @click="removeExtend(index)" class="rule_form_del">删除</a-button>
          </a-row>
        </a-form>
      </a-spin>
    </div>
  </a-modal>
</template>

<script>
import {
  relationList,
  relationRuleAdd,
  relationRuleEdit,
  relationRuleMerge
} from '@/api/modular/main/knowl/relation/relationManage'
import { propertyPage } from '@/api/modular/main/knowl/property/propertyManage'
import { register } from '@/utils/drag_modal'

export default {
  data() {
    return {
      title: undefined,
      currentRelation: undefined,
      updateId: undefined,
      strategyList: [],
      extendList: [],
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      strategyForms: [],
      extendForms: [],
      relationList: [],
      propertyAList: [],
      propertyBList: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 21 }
      },
      centerLabelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      centerWrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 }
      }
    }
  },
  methods: {
    strategyTypeChange(value, item, index) {
      item.strategyType = value
      if (value === '完全相等') {
        item.similarity = 100
      } else {
        item.similarity = undefined
      }
      this.strategyForms[index].setFieldsValue({
        similarity: item.similarity
      })
    },
    searchOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    fullStrategyName(i) {
      return '策略' + (i + 1)
    },
    removeStrategy(index) {
      this.strategyList.splice(index, 1)
      this.strategyForms.splice(index, 1)
    },
    removeExtend(index) {
      this.extendList.splice(index, 1)
      this.extendForms.splice(index, 1)
    },
    addExtend() {
      this.extendForms.push(this.$form.createForm(this))
      this.extendList.push({})
    },
    addStrategy() {
      const lastForm = this.$form.createForm(this)
      const last = {
        strategyType: '相似度'
      }
      this.strategyForms.push(lastForm)
      const relation = this.currentRelation
      if (relation) {
        last.conceptBName = relation.schemaToName
        last.conceptB = relation.schemaTo
        last.conceptAName = relation.schemaFromName
        last.conceptA = relation.schemaFrom
        this.strategyList.push(last)
      } else {
        this.strategyList.push(last)
      }
    },
    edit(item) {
      this.visible = true
      this.updateId = item.id
      this.title = '修改规则'
      register(true)
      this.confirmLoading = true
      relationRuleMerge({}, { id: item.id })
        .then((res) => {
          this.fillValue(res)
        })
        .catch((e) => {
          console.log(e)
          this.$message.error('获取信息失败!')
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    add() {
      this.visible = true
      this.title = '添加规则'
      this.updateId = undefined
      register(true)
      this.confirmLoading = true
      relationList({})
        .then((data) => {
          this.relationList = data.data
        })
        .catch((e) => {
          console.log(e)
          this.$message.error('加载失败!')
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },

    loadProperty(schemaId, schemaType) {
      this.confirmLoading = true
      propertyPage({
        'schemaId': schemaId
      })
        .then((data) => {
          if (schemaType === 1) {
            this.propertyAList = data.data.rows
          } else {
            this.propertyBList = data.data.rows
          }
        })
        .catch((e) => {
          console.log(e)
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },

    relationChange(value) {
      const item = this.relationList.find((it) => it.id === value)
      this.currentRelation = item
      this.strategyList.forEach((it) => {
        it.conceptBName = item.schemaToName
        it.conceptB = item.schemaTo
        it.conceptAName = item.schemaFromName
        it.conceptA = item.schemaFrom
      })
      this.propertyAList = []
      this.propertyBList = []
      this.strategyForms.forEach(it => {
        it.setFieldsValue({
          propertyA: undefined,
          propertyB: undefined
        })
      })
      this.extendForms.forEach(it => {
        it.setFieldsValue({
          propertyA: undefined,
          propertyB: undefined
        })
      })
      this.loadProperty(item.schemaFrom, 1)
      this.loadProperty(item.schemaTo, 2)
    },
    handleSubmit() {
      if (this.strategyList.length <= 0) {
        this.$message.error('策略信息不能为空!')
        return
      }
      // if (this.extendList.length <= 0) {
      //   this.$message.error('扩展信息不能为空!')
      //   return
      // }
      const forms = []
      forms.push(this.form)
      const strategyForms = forms.concat(this.strategyForms, this.extendForms)
      const errorList = []
      for (const form of strategyForms) {
        form.validateFields(err => {
          if (err) {
            errorList.push(true)
          }
        })
      }
      if (errorList.length <= 0) {
        const strategyList = []
        for (let i = 0; i < this.strategyForms.length; i++) {
          const form = this.strategyForms[i]
          strategyList.push(Object.assign(form.getFieldsValue(), {
            name: '策略' + (i + 1),
            conceptA: this.strategyList[i].conceptA,
            conceptB: this.strategyList[i].conceptB,
            similarity: this.strategyList[i].similarity
          }))
        }
        const extendList = []
        this.extendForms.forEach(it => extendList.push(it.getFieldsValue()))
        const relationId = this.form.getFieldsValue()['relationId']
        const relationName = this.relationList.find((it) => it.id === relationId).chName
        const parameter = {
          relationId: relationId,
          relationName: relationName,
          ruleType: '相等规则',
          id: this.updateId,
          strategyList: JSON.stringify(strategyList),
          extendList: JSON.stringify(extendList)
        }
        if (this.updateId) {
          this.updateRelationRule(parameter)
        } else {
          this.insertRelationRule(parameter)
        }
      }
    },
    updateRelationRule(parameter) {
      this.confirmLoading = true
      relationRuleEdit(parameter)
        .then((res) => {
          if (res.success) {
            this.$message.success('修改成功')
            this.$emit('ok')
            this.handleCancel()
          } else {
            this.$message.error('修改失败')
          }
        })
        .catch(() => {
          this.$message.error('修改失败')
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    insertRelationRule(parameter) {
      this.confirmLoading = true
      relationRuleAdd(parameter)
        .then((res) => {
          if (res.success) {
            this.$message.success('新增成功')
            this.$emit('ok')
            this.handleCancel()
          } else {
            this.$message.error('新增失败')
          }
        })
        .catch(() => {
          this.$message.error('新增失败')
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    modalWidth() {
      return document.body.clientWidth * 0.5
    },
    modalHeight() {
      return (document.body.clientHeight * 0.8) + 'px'
    },

    handleCancel() {
      this.visible = false
      this.form.resetFields()
      this.strategyForms = []
      register(false)
      this.extendForms = []
      this.strategyList = []
      this.currentRelation = undefined
      this.extendList = []
      this.propertyAList = []
      this.propertyBList = []
    },
    modalStyle() {
      return {
        'overflow-y': 'overlay',
        'overflow-x': 'hidden',
        'height': '100%',
        'max-height': '100%',
        'padding-right': '9px'
      }
    },
    fillValue(res) {
      this.relationList = res.relation
      const detail = res.relationRule
      this.propertyAList = detail.propertyAList
      this.propertyBList = detail.propertyBList
      this.currentRelation = this.relationList.find((it) => it.id === detail.relationId)
      this.form.setFieldsValue({ relationId: detail.relationId })
      this.setStrategyList(detail)
      this.setExtendList(detail)
    },
    setExtendList(detail) {
      const extendList = JSON.parse(detail.extendList)
      extendList.forEach(() => {
        this.extendList.push({})
        this.extendForms.push(this.$form.createForm(this))
      })
      for (let i = 0; i < extendList.length; i++) {
        const form = this.extendForms[i]
        const item = extendList[i]
        this.$nextTick(() => {
          form.setFieldsValue({
            tableName: item.tableName,
            strategyName: item.strategyName,
            columnA: item.columnA,
            columnB: item.columnB,
            propertyB: item.propertyB,
            propertyA: item.propertyA
          })
        })
      }
    },
    setStrategyList(detail) {
      const strategys = JSON.parse(detail.strategyList)
      strategys.forEach((it) => {
        this.strategyList.push({
          id: it.id,
          conceptA: it.conceptA,
          conceptB: it.conceptB,
          conceptAName: detail.conceptAName,
          conceptBName: detail.conceptBName,
          strategyType: it.strategyType,
          similarity: it.similarity
        })
        this.strategyForms.push(this.$form.createForm(this))
      })
      for (let i = 0; i < strategys.length; i++) {
        const form = this.strategyForms[i]
        const item = strategys[i]
        this.$nextTick(() => {
          form.setFieldsValue({
            strategyType: item.strategyType,
            propertyB: item.propertyB,
            propertyA: item.propertyA
          })
        })
      }
    }
  }
}
</script>

<style scoped>
.ant-advanced-search-form {
  border: 1px solid #d9d9d9;
  padding: 9px;
  margin-top: 10px;
  margin-right: 10px;
}

.ant-advanced-search-form .ant-form-item {
  display: flex;
}

::-webkit-scrollbar {
  width: 6px;
  background-color: rgba(240, 240, 240, 1);
}

.rule_form_del {
  float: right;
  margin-right: 0;
  margin-top: -12px;
  margin-bottom: 5px;
}
</style>
